package com.anfeng.cms.api.emp;

import com.anfeng.cms.api.support.ConstEum;
import com.anfeng.cms.api.support.ResDto;
import com.anfeng.cms.common.Common;
import com.anfeng.cms.domain.attendance.AfRosterDetail;
import com.anfeng.cms.domain.attendance.AfRosterInfo;
import com.anfeng.cms.domain.emp.*;
import com.anfeng.cms.domain.org.AfDepartment;
import com.anfeng.cms.domain.org.AfJob;
import com.anfeng.cms.domain.org.AfPost;
import com.anfeng.cms.export.ExportEmployeeExcel;
import com.anfeng.cms.export.ExportGuestInfoExcel;
import com.anfeng.cms.export.ExportRosterDetailExcel;
import com.anfeng.cms.export.ExportUploadImageErrorInfoExcel;
import com.anfeng.cms.request.emp.*;
import com.anfeng.cms.service.attendance.IAfRosterDetailService;
import com.anfeng.cms.service.attendance.IAfRosterInfoService;
import com.anfeng.cms.service.emp.*;
import com.anfeng.cms.service.impl.ExcelSupport;
import com.anfeng.cms.service.org.IAfDepartmentService;
import com.anfeng.cms.service.org.IAfJobService;
import com.anfeng.cms.service.org.IAfPostService;
import com.anfeng.cms.util.IdGeneratorUtil;
import com.anfeng.cms.util.JsonMapper;
import com.anfeng.cms.util.base.POIUtil;
import com.anfeng.cms.util.time.WorkAgeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 吴朋
 * @date 2019/7/16
 */
@RestController
@RequestMapping(value = "/api/employee", name = "员工管理")
@Slf4j
public class EmployeeManagerEndPoint {

    @Autowired
    private IAfEmployeeInfoService employeeInfoService;
    @Autowired
    private IAfGuestInfoService guestInfoService;

    @Autowired
    private ExcelSupport excelSupport;
    @Autowired
    private IAfFaceInfoService faceInfoService;
    @Autowired
    private IAfRosterInfoService rosterInfoService;
    @Autowired
    private IAfRosterDetailService rosterDetailService;
    @Autowired
    private UploadImageService uploadImageService;
    @Autowired
    private IAfEmployeePhotoService employeePhotoService;
    @Autowired
    private IAfPhotoImpLogService photoImpLogService;
    @Autowired
    private IAfGuestLogService guestLogService;
    @Autowired
    private IAfDepartmentService departmentService;
    @Autowired
    private IAfPostService postService;
    @Autowired
    private IAfJobService jobService;

    @GetMapping(value = "/info")
    @ResponseBody
    public ResDto getEmployeeInfo(EmployeeInfoReq req) {
        if (null == req) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        if (req.getPage() < 1) {
            req.setPage(1);
        }
        if (req.getPageSize() < 10) {
            req.setPageSize(10);
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("current_page", req.getPage());
        resultMap.put("size", req.getPageSize());
        int infoCounts = employeeInfoService.getEmployeeInfoCounts(req);
        int total = (infoCounts - 1) / req.getPageSize() + 1;
        resultMap.put("total_page", total);
        resultMap.put("totals", infoCounts);
        List<EmployeeInfoDTO> infoDTOS = new ArrayList<>();
        if (infoCounts > 0) {
            List<AfEmployeeInfo> employeeInfos = employeeInfoService.getEmployeeInfosByPage(req, req.getPage(), req.getPageSize());
            if (null != employeeInfos && !employeeInfos.isEmpty()) {
                infoDTOS = employeeInfos.stream().map(employeeInfo -> {
                    EmployeeInfoDTO dto = new EmployeeInfoDTO();
                    BeanUtils.copyProperties(employeeInfo, dto);
                    //补充工龄
                    int workAge = WorkAgeUtil.getWorkAgeLength(employeeInfo.getHireDate(), employeeInfo.getDismissalDate());
                    dto.setWorkAge(workAge);
                    if(StringUtils.isNotBlank(employeeInfo.getDeptId())) {
                        dto.setDeptName(getDeptName(employeeInfo.getDeptId()));
                    }
                    if (StringUtils.isNotBlank(employeeInfo.getPostId())) {
                        dto.setPostName(getPostName(employeeInfo.getPostId()));
                    }
                    if (StringUtils.isNotBlank(employeeInfo.getJobId())) {
                        dto.setJobName(getJobName(employeeInfo.getJobId()));
                    }
                    return dto;
                }).collect(Collectors.toList());
            }
        }
        resultMap.put("datas", infoDTOS);
        ResDto resDto = new ResDto(ConstEum.SUCCESS);
        resDto.setDatas(JsonMapper.defaultMapper().toJson(resultMap));
        return resDto;
    }

    @GetMapping(value = "/info/export")
    public void exportEmployee(EmployeeInfoReq req, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        List<AfEmployeeInfo> employeeInfos = employeeInfoService.getAllEmployeeInfo(req);
        List<ExportEmployeeExcel> infoDTOS = new ArrayList<>();
        if (null != employeeInfos && !employeeInfos.isEmpty()) {
            infoDTOS = employeeInfos.stream().map(employeeInfo -> {
                ExportEmployeeExcel dto = new ExportEmployeeExcel();
                BeanUtils.copyProperties(employeeInfo, dto);
                int workAge = WorkAgeUtil.getWorkAgeLength(employeeInfo.getHireDate(), employeeInfo.getDismissalDate());
                dto.setWorkAge(workAge);
                if(StringUtils.isNotBlank(employeeInfo.getDeptId())) {
                    dto.setDeptName(getDeptName(employeeInfo.getDeptId()));
                }
                if (StringUtils.isNotBlank(employeeInfo.getPostId())) {
                    dto.setPostName(getPostName(employeeInfo.getPostId()));
                }
                if (StringUtils.isNotBlank(employeeInfo.getJobId())) {
                    dto.setJobName(getJobName(employeeInfo.getJobId()));
                }
                return dto;
            }).collect(Collectors.toList());
        }
        ExcelSupport.Content<ExportEmployeeExcel> content = new ExcelSupport.Content<>("员工信息", infoDTOS, ExportEmployeeExcel.class);
        excelSupport.export(httpServletRequest, httpServletResponse, "员工信息.xls", content);
    }


    @GetMapping(value = "/guest")
    @ResponseBody
    public ResDto getGuestInfo(GuestInfoReq req) {
        if (null == req) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        if (req.getPage() < 1) {
            req.setPage(1);
        }
        if (req.getPageSize() < 10) {
            req.setPageSize(10);
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("current_page", req.getPage());
        resultMap.put("size", req.getPageSize());
        int infoCounts = guestInfoService.getAllGuestInfoCounts(req);
        int total = (infoCounts - 1) / req.getPageSize() + 1;
        resultMap.put("total_page", total);
        resultMap.put("totals", infoCounts);
        List<GuestInfoDTO> infoDTOS = new ArrayList<>();
        if (infoCounts > 0) {
            List<AfGuestInfo> guestInfos = guestInfoService.getGuestInfoByPage(req, req.getPage(), req.getPageSize());
            if (null != guestInfos && !guestInfos.isEmpty()) {
                infoDTOS = guestInfos.stream().map(guestInfo -> {
                    GuestInfoDTO dto = new GuestInfoDTO();
                    BeanUtils.copyProperties(guestInfo, dto);
                    return dto;
                }).collect(Collectors.toList());
            }
        }
        resultMap.put("datas", infoDTOS);
        ResDto resDto = new ResDto(ConstEum.SUCCESS);
        resDto.setDatas(JsonMapper.defaultMapper().toJson(resultMap));
        return resDto;
    }

    @GetMapping(value = "/guest/export")
    public void exportGuest(GuestInfoReq req, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        List<AfGuestInfo> guestInfos = guestInfoService.getAllGuestInfos(req);
        List<ExportGuestInfoExcel> infoDTOS = new ArrayList<>();
        if (null != guestInfos && !guestInfos.isEmpty()) {
            infoDTOS = guestInfos.stream().map(guestInfo -> {
                ExportGuestInfoExcel dto = new ExportGuestInfoExcel();
                BeanUtils.copyProperties(guestInfo, dto);
                return dto;
            }).collect(Collectors.toList());
        }
        ExcelSupport.Content<ExportGuestInfoExcel> content = new ExcelSupport.Content<>("访客管理", infoDTOS, ExportGuestInfoExcel.class);
        excelSupport.export(httpServletRequest, httpServletResponse, "访客信息.xls", content);
    }

    @GetMapping(value = "/face")
    @ResponseBody
    public ResDto getFaceInfo(EmployeeFaceInfoReq faceInfoReq) {
        if (null == faceInfoReq) {
            faceInfoReq = new EmployeeFaceInfoReq();
        }
        if (faceInfoReq.getPage() == null || faceInfoReq.getPage() < 1) {
            faceInfoReq.setPage(1);
        }
        if (faceInfoReq.getPageSize() == null || faceInfoReq.getPageSize() < 10) {
            faceInfoReq.setPageSize(10);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("current_page", faceInfoReq.getPage());
        resultMap.put("size", faceInfoReq.getPageSize());
        int infoCounts = faceInfoService.getFaceInfoCounts(faceInfoReq);
        int total = (infoCounts - 1) / faceInfoReq.getPageSize() + 1;
        resultMap.put("total_page", total);
        resultMap.put("totals", infoCounts);
        List<EmployeeFaceInfoDTO> infoDTOS = new ArrayList<>();
        if (infoCounts > 0) {
            List<AfFaceInfo> guestInfos = faceInfoService.getFaceInfosByPage(faceInfoReq, faceInfoReq.getPage(), faceInfoReq.getPageSize());
            if (null != guestInfos && !guestInfos.isEmpty()) {
                infoDTOS = guestInfos.stream().map(faceInfo -> {
                    EmployeeFaceInfoDTO dto = new EmployeeFaceInfoDTO();
                    BeanUtils.copyProperties(faceInfo, dto);
                    return dto;
                }).collect(Collectors.toList());
            }
        }
        resultMap.put("datas", infoDTOS);
        ResDto resDto = new ResDto(ConstEum.SUCCESS);
        resDto.setDatas(JsonMapper.defaultMapper().toJson(resultMap));
        return resDto;
    }


    @GetMapping(value = "/schedule")
    @ResponseBody
    public ResDto getSchedule(RosterInfoReq rosterInfoReq) {
        if (null == rosterInfoReq) {
            rosterInfoReq = new RosterInfoReq();
        }
        if (rosterInfoReq.getPage() == null || rosterInfoReq.getPage() < 1) {
            rosterInfoReq.setPage(1);
        }
        if (rosterInfoReq.getPageSize() == null || rosterInfoReq.getPageSize() < 10) {
            rosterInfoReq.setPageSize(10);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("current_page", rosterInfoReq.getPage());
        resultMap.put("size", rosterInfoReq.getPageSize());
        int infoCounts = rosterInfoService.getAfRosterInfoCounts(rosterInfoReq);
        int total = (infoCounts - 1) / rosterInfoReq.getPageSize() + 1;
        resultMap.put("total_page", total);
        resultMap.put("totals", infoCounts);
        List<RosterInfoDTO> infoDTOS = new ArrayList<>();
        if (infoCounts > 0) {
            List<AfRosterInfo> rosterInfos = rosterInfoService.getRosterInfosByPage(rosterInfoReq, rosterInfoReq.getPage(), rosterInfoReq.getPageSize());
            if (null != rosterInfos && !rosterInfos.isEmpty()) {
                infoDTOS = rosterInfos.stream().map(rosterInfo -> {
                    RosterInfoDTO dto = new RosterInfoDTO();
                    dto.setId(rosterInfo.getId());
                    dto.setCross(rosterInfo.getCross());
                    dto.setName(rosterInfo.getName());
                    int persons = rosterDetailService.getRosterInfoDetailCounts(rosterInfo.getId());
                    dto.setPersons(persons);
                    return dto;
                }).collect(Collectors.toList());
            }
        }
        resultMap.put("datas", infoDTOS);
        ResDto resDto = new ResDto(ConstEum.SUCCESS);
        resDto.setDatas(JsonMapper.defaultMapper().toJson(resultMap));
        return resDto;
    }

    @PostMapping(value = "/add")
    @ResponseBody
    public ResDto addEmployee(AddEmployeeInfoDTO infoDTO) {
        ResDto resDto;
        if (null == infoDTO) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 先校验信息
        if (StringUtils.isBlank(infoDTO.getName()) || StringUtils.isBlank(infoDTO.getDeptId()) || StringUtils.isBlank(infoDTO.getDeptName())
                || StringUtils.isBlank(infoDTO.getEmpNo()) || StringUtils.isBlank(infoDTO.getIdentityNo())
                || StringUtils.isBlank(infoDTO.getJobId()) || StringUtils.isBlank(infoDTO.getJobName()) ||
                StringUtils.isBlank(infoDTO.getMobile()) || StringUtils.isBlank(infoDTO.getPostId()) || StringUtils.isBlank(infoDTO.getPostName()) ||
                StringUtils.isBlank(infoDTO.getIdentityNo()) ||
                (infoDTO.getGender() != Common.GENDER_MALE && infoDTO.getGender() != Common.GENDER_FEMALE)
                || infoDTO.getHireDate() == null) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 根据手机号 证件号 员工编号 查询是否存在
        List<AfEmployeeInfo> employeeInfos = employeeInfoService.getEmployeeInfo(infoDTO.getEmpNo(), infoDTO.getMobile(), infoDTO.getIdentityNo());
        if (null != employeeInfos && !employeeInfos.isEmpty()) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("已存在相同手机号或证件号或员工号");
            return resDto;
        }
        AfEmployeeInfo employeeInfo = new AfEmployeeInfo();
        employeeInfo.setIdentityNo(infoDTO.getIdentityNo());
        employeeInfo.setDeptId(infoDTO.getDeptId());
        employeeInfo.setDeptName(infoDTO.getDeptName());
        employeeInfo.setStatus(Common.EMPLOYEE_STATUS_WORKING);
        employeeInfo.setName(infoDTO.getName());
        employeeInfo.setMobile(infoDTO.getMobile());
        employeeInfo.setEmpNo(infoDTO.getEmpNo());
        employeeInfo.setDismissalDate(null);
        employeeInfo.setGender(infoDTO.getGender());
        Date hireDate = new Date();
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            hireDate = dateFormat.parse(infoDTO.getHireDate());
        } catch (Exception e) {

        }
        employeeInfo.setHireDate(hireDate);
        employeeInfo.setJobId(infoDTO.getJobId());
        employeeInfo.setJobName(infoDTO.getJobName());
        employeeInfo.setPostId(infoDTO.getPostId());
        employeeInfo.setPostName(infoDTO.getPostName());
        // 新增
        String employeeId = employeeInfoService.addEmployee(employeeInfo);
        if (StringUtils.isBlank(employeeId)) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("新增员工出现失败");
            return resDto;
        }
        if (StringUtils.isBlank(infoDTO.getPhotoId())) {
            resDto = new ResDto(ConstEum.SUCCESS);
            return resDto;
        }
        // 更新图片信息
        AfEmployeePhoto employeePhoto = employeePhotoService.selectById(infoDTO.getPhotoId());
        if (null == employeePhoto) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("根据图片id未查到相关图片");
            return resDto;
        }
        employeePhoto.setEmpId(employeeId);
        employeePhoto.setModifiedTime(new Date());
        boolean result = employeePhotoService.updateById(employeePhoto);
        if (!result) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("更新图片信息失败");
            return resDto;
        }
        // 新增人员faceInfo
        AfFaceInfo faceInfo = faceInfoService.getFaceInfoByEmpNo(employeeInfo.getEmpNo());
        if (faceInfo == null) {
            faceInfo = new AfFaceInfo();
            faceInfo.setPhotoId(infoDTO.getPhotoId());
            faceInfo.setState(Common.DATA_STATE_NORMAL);
            faceInfo.setEmpNo(employeeInfo.getEmpNo());
            faceInfo.setStatus(employeeInfo.getStatus());
            faceInfo.setIdentityNo(employeeInfo.getIdentityNo());
            faceInfo.setDeptId(employeeInfo.getDeptId());
            faceInfo.setDeptName(employeeInfo.getDeptName());
            faceInfo.setMobile(employeeInfo.getMobile());
            faceInfo.setEmpName(employeeInfo.getName());
            faceInfo.setEmpId(employeeInfo.getId());
            String faceInfoId = faceInfoService.addFaceInfo(faceInfo);
            if (StringUtils.isBlank(faceInfoId)) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("新增人脸信息失败");
                return resDto;
            }
            faceInfo.setId(faceInfoId);
        } else {
            int updateInfo = faceInfoService.updateFaceInfoPhoto(employeeInfo.getEmpNo(), infoDTO.getPhotoId());
            if (updateInfo == Common.RETURN_FAILED) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("更新人脸信息失败");
                return resDto;
            }
        }
        resDto = new ResDto(ConstEum.SUCCESS);
        return resDto;
    }

    @PostMapping(value = "/upload/single")
    @ResponseBody
    public ResDto uploadPhoto(MultipartFile file) {
        ResDto resDto;
        if (file.getSize() > Common.UPLOAD_PIC_MAX_LENGTH) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("上传图片超过1M");
            return resDto;
        }
        String imageId = null;
        try {
            // 新增成功 上传图片
            imageId = uploadImageService.saveImage(Common.PERSON_ROLE_TYPE_EMPLOYEE, null, file.getOriginalFilename(), file.getBytes());
            if (StringUtils.isBlank(imageId)) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("上传图片失败");
            } else {
                resDto = new ResDto(ConstEum.SUCCESS);
                resDto.setDatas(imageId);
            }
        } catch (Exception e) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg(e.getMessage());
        }
        return resDto;
    }

    @GetMapping(value = "/info/download/template")
    @ResponseBody
    public void loadLoadInfoTemplete(HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        excelSupport.downLoadTemplete(httpServletRequest, httpServletResponse, "employee.xls");
    }

    @PostMapping(value = "/import/infos")
    @ResponseBody
    public ResDto importEmployeeInfos(MultipartFile file) {
        ResDto resDto;
        if (null == file) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        String fileName = file.getOriginalFilename();
        try {
            Map<String, Object> readExcelEmployeeInfo = POIUtil.readExcelEmployee(file.getBytes(), fileName);
            if (null == readExcelEmployeeInfo || readExcelEmployeeInfo.isEmpty()) {
                return new ResDto(ConstEum.PARAM_ERROR);
            }
            List<AfEmployeeInfo> employeeInfos = (List<AfEmployeeInfo>) readExcelEmployeeInfo.get("employeeInfos");
            if (null == employeeInfos || employeeInfos.isEmpty()) {
                return new ResDto(ConstEum.PARAM_ERROR);
            }
            List<String> errorEmp = new ArrayList<>();
            for (AfEmployeeInfo employeeInfo : employeeInfos) {
                String empId = employeeInfoService.addEmployee(employeeInfo);
                if(StringUtils.isBlank(empId)) {
                    errorEmp.add(employeeInfo.getEmpNo());
                } else {
                    //新增人脸信息
                    // 新增人员faceInfo
                    AfFaceInfo faceInfo = faceInfoService.getFaceInfoByEmpNo(employeeInfo.getEmpNo());
                    if (faceInfo == null) {
                        faceInfo = new AfFaceInfo();
                        faceInfo.setState(Common.DATA_STATE_NORMAL);
                        faceInfo.setEmpNo(employeeInfo.getEmpNo());
                        faceInfo.setStatus(employeeInfo.getStatus());
                        faceInfo.setIdentityNo(employeeInfo.getIdentityNo());
                        faceInfo.setDeptId(employeeInfo.getDeptId());
                        faceInfo.setDeptName(employeeInfo.getDeptName());
                        faceInfo.setMobile(employeeInfo.getMobile());
                        faceInfo.setEmpName(employeeInfo.getName());
                        faceInfo.setEmpId(employeeInfo.getId());
                        String faceInfoId = faceInfoService.addFaceInfo(faceInfo);
                        if (StringUtils.isBlank(faceInfoId)) {
                            log.error("新增员工人脸失败 {}", employeeInfo.getEmpNo());
                        }
                    }
                }
            }
            if (errorEmp.isEmpty()) {
                return new ResDto(ConstEum.SUCCESS);
            }
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("导入失败");
            resDto.setDatas(JsonMapper.defaultMapper().toJson(errorEmp));
            return resDto;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResDto(ConstEum.SERVER_ERROR);
    }

    @PostMapping(value = "/upload/multi")
    @ResponseBody
    public ResDto uploadPhotoBatch(MultipartFile file) {
        ResDto resDto;
        AfPhotoImpLog impLog = new AfPhotoImpLog();
        if (file.getSize() > Common.UPLOAD_PIC_MAX_LENGTH) {
            impLog.setSuccess(Common.UPLOAD_IMAGE_FAILED);
            impLog.setRemark("图片超过1M");
            impLog.setpName(file.getOriginalFilename());
            String logId = photoImpLogService.addPhotoImpLog(impLog);
            if (StringUtils.isBlank(logId)) {
                log.error("插入导入图片日志失败 {}", JsonMapper.defaultMapper().toJson(impLog));
            }
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("上传图片超过1M");
            return resDto;
        }
        // 先根据图片名获取员工信息
        String fileOriginalFilename = file.getOriginalFilename();
        //截取 员工号
        String empNo = fileOriginalFilename.substring(0, fileOriginalFilename.indexOf("."));
        AfEmployeeInfo employeeInfo = employeeInfoService.getEmployeeInfoByEmpNo(empNo);
        if (null == employeeInfo) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("未查询到相关人员");
            impLog.setpName(fileOriginalFilename);
            impLog.setRemark("未查询到相关人员");
            impLog.setSuccess(Common.UPLOAD_IMAGE_FAILED);
        } else {
            String imageId = null;
            try {
                // 新增成功 上传图片
                imageId = uploadImageService.saveImage(Common.PERSON_ROLE_TYPE_EMPLOYEE, employeeInfo.getId(), file.getOriginalFilename(), file.getBytes());
                if (StringUtils.isBlank(imageId)) {
                    resDto = new ResDto(ConstEum.SERVER_ERROR);
                    resDto.setMsg("上传图片失败");
                    impLog.setSuccess(Common.UPLOAD_IMAGE_FAILED);
                    impLog.setRemark("上传图片失败");
                } else {
                    resDto = new ResDto(ConstEum.SUCCESS);
                    impLog.setSuccess(Common.UPLOAD_IMAGE_SUCCESS);
                    impLog.setRemark("成功");
                    impLog.setpId(imageId);
                }
                // 查看人脸信息是否存在 如果不存在就新增
                AfFaceInfo afFaceInfo = faceInfoService.getFaceInfoByEmpNo(empNo);
                if (afFaceInfo == null) {
                    afFaceInfo = new AfFaceInfo();
                    afFaceInfo.setPhotoId(imageId);
                    afFaceInfo.setState(Common.DATA_STATE_NORMAL);
                    afFaceInfo.setEmpNo(empNo);
                    afFaceInfo.setStatus(employeeInfo.getStatus());
                    afFaceInfo.setIdentityNo(employeeInfo.getIdentityNo());
                    afFaceInfo.setDeptId(employeeInfo.getDeptId());
                    afFaceInfo.setDeptName(employeeInfo.getDeptName());
                    afFaceInfo.setMobile(employeeInfo.getMobile());
                    afFaceInfo.setEmpName(employeeInfo.getName());
                    afFaceInfo.setEmpId(employeeInfo.getId());
                    String faceInfoId = faceInfoService.addFaceInfo(afFaceInfo);
                    afFaceInfo.setId(faceInfoId);
                }
                int updateFaceInfoPhoto = faceInfoService.updateFaceInfoPhoto(empNo, imageId);
                if (updateFaceInfoPhoto == Common.RETURN_FAILED) {
                    log.error("更新员工人脸信息失败");
                }
            } catch (Exception e) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg(e.getMessage());
                impLog.setSuccess(Common.UPLOAD_IMAGE_FAILED);
                impLog.setRemark("上传出现异常");
            }
        }
        impLog.setpName(fileOriginalFilename);
        String photoImpLogId = photoImpLogService.addPhotoImpLog(impLog);
        if (StringUtils.isBlank(photoImpLogId)) {
            log.error("新增导入图片日志失败 {}", JsonMapper.defaultMapper().toJson(impLog));
        }
        return resDto;
    }

    @GetMapping(value = "/upload/export")
    @ResponseBody
    public void exportUploadErrorInfo(HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        List<AfPhotoImpLog> failedImpLogs = photoImpLogService.getAllFailedImpLogs();
        List<ExportUploadImageErrorInfoExcel> errorInfoExcels = new ArrayList<>();
        if (null != failedImpLogs && !failedImpLogs.isEmpty()) {
            errorInfoExcels = failedImpLogs.stream().map(photoImpLog -> {
                ExportUploadImageErrorInfoExcel excel = new ExportUploadImageErrorInfoExcel();
                excel.setPhotoName(photoImpLog.getpName());
                excel.setRemark(photoImpLog.getRemark());
                excel.setCreateTime(photoImpLog.getCreateTime());
                return excel;
            }).collect(Collectors.toList());
        }
        ExcelSupport.Content<ExportUploadImageErrorInfoExcel> content = new ExcelSupport.Content<>("上传照片失败信息", errorInfoExcels, ExportUploadImageErrorInfoExcel.class);
        excelSupport.export(httpServletRequest, httpServletResponse, "上传照片失败信息.xls", content);
    }

    @PostMapping(value = "/upload/export/clear")
    @ResponseBody
    public ResDto clearUploadError() {
        int result = photoImpLogService.clearUploadImageFailureInfo();
        if (result == Common.RETURN_FAILED) {
            return new ResDto(ConstEum.SERVER_ERROR);
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @PostMapping(value = "/upload/faces/multi")
    @ResponseBody
    public ResDto uploadFaceBatch(MultipartFile file) {
        return this.uploadPhotoBatch(file);
    }

    @PostMapping(value = "/update/basic/pic")
    @ResponseBody
    public ResDto updateEmployeeBasicPic(@RequestParam("empNo") String empNo, MultipartFile file) {
        ResDto resDto;
        if (file.getSize() > Common.UPLOAD_PIC_MAX_LENGTH) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("上传图片超过1M");
            return resDto;
        }
        if (StringUtils.isBlank(empNo)) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("员工编号 不能为null");
            return resDto;
        }
        // 获取员工faceInfo
        AfFaceInfo afFaceInfo = faceInfoService.getFaceInfoByEmpNo(empNo);
        if (afFaceInfo == null) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("未获取人脸信息");
            return resDto;
        }
        String imageId = null;
        try {
            // 新增成功 上传图片
            imageId = uploadImageService.saveImage(Common.PERSON_ROLE_TYPE_EMPLOYEE, afFaceInfo.getEmpId(), file.getOriginalFilename(), file.getBytes());
            if (StringUtils.isBlank(imageId)) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("上传图片失败");
                return resDto;
            }
            int result = faceInfoService.updateFaceInfoBasicPhoto(empNo, imageId);
            if (result == Common.RETURN_FAILED) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("更新基础照片失败");
                log.error("更新基础照片失败 empNo:{} imageId:{}", empNo, imageId);
                return resDto;
            }
        } catch (Exception e) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg(e.getMessage());
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @PostMapping(value = "/update/other/pic")
    @ResponseBody
    public ResDto updateEmployeeOtherPic(@RequestParam("empNo") String empNo, MultipartFile file) {
        ResDto resDto;
        if (file.getSize() > Common.UPLOAD_PIC_MAX_LENGTH) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("上传图片超过1M");
            return resDto;
        }
        if (StringUtils.isBlank(empNo)) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("员工编号 不能为null");
            return resDto;
        }
        AfEmployeeInfo afEmployeeInfo = employeeInfoService.getEmployeeInfoByEmpNo(empNo);
        if (null == afEmployeeInfo) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("未获取员工信息");
            return resDto;
        }
        String imageId = null;
        try {
            // 新增成功 上传图片
            imageId = uploadImageService.saveImage(Common.PERSON_ROLE_TYPE_EMPLOYEE, afEmployeeInfo.getId(), file.getOriginalFilename(), file.getBytes());
            if (StringUtils.isBlank(imageId)) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("上传图片失败");
            } else {
                resDto = new ResDto(ConstEum.SUCCESS);
            }
        } catch (Exception e) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg(e.getMessage());
        }
        return resDto;
    }

    @PostMapping(value = "/upload/faces/guest")
    @ResponseBody
    public ResDto uploadGuestPhoto(MultipartFile file) {
        ResDto resDto;
        AfPhotoImpLog impLog = new AfPhotoImpLog();
        if (file.getSize() > Common.UPLOAD_PIC_MAX_LENGTH) {
            impLog.setSuccess(Common.UPLOAD_IMAGE_FAILED);
            impLog.setRemark("图片超过1M");
            impLog.setpName(file.getOriginalFilename());
            String logId = photoImpLogService.addPhotoImpLog(impLog);
            if (StringUtils.isBlank(logId)) {
                log.error("插入导入图片日志失败 {}", JsonMapper.defaultMapper().toJson(impLog));
            }
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("上传图片超过1M");
            return resDto;
        }
        // 先根据图片名获取员工信息
        String fileOriginalFilename = file.getOriginalFilename();
        //截取 访客手机号
        String guestMobile = fileOriginalFilename.substring(0, fileOriginalFilename.indexOf("."));
        AfGuestInfo guestInfo = guestInfoService.getGuestInfoByMobile(guestMobile);
        if (null == guestInfo) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("未查询到相关人员");
            impLog.setpName(fileOriginalFilename);
            impLog.setRemark("未查询到相关人员");
            impLog.setSuccess(Common.UPLOAD_IMAGE_FAILED);
        } else {
            String imageId = null;
            try {
                // 新增成功 上传图片
                imageId = uploadImageService.saveImage(Common.PERSON_ROLE_TYPE_GUEST, guestInfo.getId(), file.getOriginalFilename(), file.getBytes());
                if (StringUtils.isBlank(imageId)) {
                    resDto = new ResDto(ConstEum.SERVER_ERROR);
                    resDto.setMsg("上传图片失败");
                    impLog.setSuccess(Common.UPLOAD_IMAGE_FAILED);
                    impLog.setRemark("上传图片失败");
                } else {
                    guestInfo.setPhotoId(imageId);
                    guestInfo.setModifiedTime(new Date());
                    boolean update = guestInfoService.updateById(guestInfo);
                    if (!update) {
                        resDto = new ResDto(ConstEum.SERVER_ERROR);
                        impLog.setSuccess(Common.UPLOAD_IMAGE_SUCCESS);
                        impLog.setRemark("成功");
                        impLog.setpId(imageId);
                    } else {
                        resDto = new ResDto(ConstEum.SUCCESS);
                        impLog.setSuccess(Common.UPLOAD_IMAGE_SUCCESS);
                        impLog.setRemark("成功");
                        impLog.setpId(imageId);
                    }
                }
            } catch (Exception e) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg(e.getMessage());
                impLog.setSuccess(Common.UPLOAD_IMAGE_FAILED);
                impLog.setRemark("上传出现异常");
            }
        }
        impLog.setpName(fileOriginalFilename);
        String photoImpLogId = photoImpLogService.addPhotoImpLog(impLog);
        if (StringUtils.isBlank(photoImpLogId)) {
            log.error("新增导入图片日志失败 {}", JsonMapper.defaultMapper().toJson(impLog));
        }
        return resDto;
    }

    @PostMapping(value = "/guest/add")
    @ResponseBody
    public ResDto addGuestInfo(AddGuestInfoDTO addGuestInfoDTO) {
        ResDto resDto;
        if (null == addGuestInfoDTO) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 先校验信息
        if (StringUtils.isBlank(addGuestInfoDTO.getGuestName()) || StringUtils.isBlank(addGuestInfoDTO.getGuestMobile())
                || StringUtils.isBlank(addGuestInfoDTO.getGuestIdNo()) || StringUtils.isBlank(addGuestInfoDTO.getEmpMobile())
                || StringUtils.isBlank(addGuestInfoDTO.getEmpName()) ||
                (addGuestInfoDTO.getGuestGender() != Common.GENDER_MALE && addGuestInfoDTO.getGuestGender() != Common.GENDER_FEMALE)
                ) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 根据手机号 查询是否存在
        List<AfEmployeeInfo> employeeInfos = employeeInfoService.getEmployeeInfo(null, addGuestInfoDTO.getEmpMobile(), null);
        if (null == employeeInfos || employeeInfos.isEmpty()) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("未获取相关被访者信息");
            return resDto;
        }
        AfEmployeeInfo employeeInfo = employeeInfos.get(0);
        // 判断员工名是否一致
        if (!addGuestInfoDTO.getEmpName().equals(employeeInfo.getName())) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("被访者手机号和名称不一致");
            return resDto;
        }
        //根据被访者信息获取被访者对象
        AfGuestInfo afGuestInfo = guestInfoService.getGuestInfoByMobile(addGuestInfoDTO.getGuestMobile());
        if (null != afGuestInfo) {
            afGuestInfo.setEmpId(employeeInfo.getId());
            afGuestInfo.setEmpName(addGuestInfoDTO.getEmpName());
            afGuestInfo.setEmpMobile(addGuestInfoDTO.getEmpMobile());
        } else {
            // 不存在新增
            afGuestInfo = new AfGuestInfo();
            afGuestInfo.setState(Common.DATA_STATE_NORMAL);
            afGuestInfo.setName(addGuestInfoDTO.getGuestName());
            afGuestInfo.setIdentityNo(addGuestInfoDTO.getGuestIdNo());
            afGuestInfo.setMobile(addGuestInfoDTO.getGuestMobile());
            afGuestInfo.setGender(addGuestInfoDTO.getGuestGender());

            afGuestInfo.setEmpId(employeeInfo.getId());
            afGuestInfo.setEmpMobile(addGuestInfoDTO.getEmpMobile());
            afGuestInfo.setEmpName(addGuestInfoDTO.getEmpName());
        }
        String guestId = guestInfoService.addGuestInfo(afGuestInfo);
        if (StringUtils.isBlank(guestId)) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("新增访客信息失败");
            return resDto;
        }
        // 成功之后 增加流水
        AfGuestLog guestLog = new AfGuestLog();
        guestLog.setGuestId(guestId);
        guestLog.setEmpName(addGuestInfoDTO.getEmpName());
        guestLog.setEmpId(employeeInfo.getId());
        guestLog.setEmpMobile(addGuestInfoDTO.getEmpMobile());
        guestLog.setState(Common.DATA_STATE_NORMAL);
        String addGuestLogId = guestLogService.addGuestLog(guestLog);
        if (StringUtils.isBlank(addGuestLogId)) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("新增访客日志信息失败");
            return resDto;
        }
        resDto = new ResDto(ConstEum.SUCCESS);
        return resDto;
    }

    @PostMapping(value = "/guest/state")
    @ResponseBody
    public ResDto managerGuestState(String guestId, Integer state) {
        ResDto resDto;
        if (StringUtils.isBlank(guestId) || state == null || (state != Common.DATA_STATE_NORMAL && state != Common.DATA_STATE_DELETE)) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            return resDto;
        }
        //获取访客状态
        AfGuestInfo afGuestInfo = guestInfoService.selectById(guestId);
        if (null == afGuestInfo) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("未获取到相关访客");
            return resDto;
        }
        if (state == Common.DATA_STATE_NORMAL) {
            afGuestInfo.setState(Common.DATA_STATE_DELETE);
        } else {
            afGuestInfo.setState(Common.DATA_STATE_NORMAL);
        }
        afGuestInfo.setModifiedTime(new Date());

        boolean update = guestInfoService.updateById(afGuestInfo);
        if (!update) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("更新访客状态失败");
            return resDto;
        }
        resDto = new ResDto(ConstEum.SUCCESS);
        resDto.setDatas(afGuestInfo.getState()+"");
        return resDto;
    }

    @PostMapping(value = "/upload/guest/single")
    @ResponseBody
    public ResDto uploadSingleGuestPhoto(String guestId, MultipartFile file) {
        ResDto resDto;
        if (file.getSize() > Common.UPLOAD_PIC_MAX_LENGTH) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("上传图片超过1M");
            return resDto;
        }
        // 先根据图片名获取员工信息
        AfGuestInfo guestInfo = guestInfoService.selectById(guestId);
        if (null == guestInfo) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("未查询到相关人员");
        } else {
            String imageId = null;
            try {
                // 新增成功 上传图片
                imageId = uploadImageService.saveImage(Common.PERSON_ROLE_TYPE_GUEST, guestInfo.getId(), file.getOriginalFilename(), file.getBytes());
                if (StringUtils.isBlank(imageId)) {
                    resDto = new ResDto(ConstEum.SERVER_ERROR);
                    resDto.setMsg("上传图片失败");
                } else {
                    guestInfo.setPhotoId(imageId);
                    guestInfo.setModifiedTime(new Date());
                    boolean update = guestInfoService.updateById(guestInfo);
                    if (!update) {
                        resDto = new ResDto(ConstEum.SERVER_ERROR);
                    } else {
                        resDto = new ResDto(ConstEum.SUCCESS);
                    }
                }
            } catch (Exception e) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg(e.getMessage());
            }
        }
        return resDto;
    }

    @PostMapping(value = "/leave")
    @ResponseBody
    public ResDto batchEmployeeLeave(String ids) {
        if (StringUtils.isBlank(ids)) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        String[] strings = ids.split(",");
        List<AfEmployeeInfo> employeeInfos = new ArrayList<>();
        for (String id : strings) {
            AfEmployeeInfo employeeInfo = employeeInfoService.selectById(id);
            if (null == employeeInfo) {
                ResDto resDto = new ResDto(ConstEum.PARAM_ERROR);
                resDto.setMsg("未获取到相关员工");
                return resDto;
            }
            //已经离职
            if (employeeInfo.getStatus() == Common.EMPLOYEE_STATUS_DIMISSION) {
                continue;
            }
            if (employeeInfo.getStatus() == Common.EMPLOYEE_STATUS_WORKING || employeeInfo.getStatus() == Common.EMPLOYEE_STATUS_VOCATION) {
                employeeInfo.setStatus(Common.EMPLOYEE_STATUS_DIMISSION);
                employeeInfo.setModifiedTime(new Date());
                employeeInfo.setDismissalDate(new Date());
                employeeInfos.add(employeeInfo);
            }
        }
        if (!employeeInfos.isEmpty()) {
            boolean updateInfo = employeeInfoService.updateBatchById(employeeInfos);
            if (!updateInfo) {
                ResDto resDto = new ResDto(ConstEum.PARAM_ERROR);
                resDto.setMsg("修改失败");
                return resDto;
            }
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @PostMapping(value = "/working")
    @ResponseBody
    public ResDto batchEmployeeWorking(String ids) {
        if (StringUtils.isBlank(ids)) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        String[] strings = ids.split(",");
        List<AfEmployeeInfo> employeeInfos = new ArrayList<>();
        for (String id : strings) {
            AfEmployeeInfo employeeInfo = employeeInfoService.selectById(id);
            if (null == employeeInfo) {
                ResDto resDto = new ResDto(ConstEum.PARAM_ERROR);
                resDto.setMsg("未获取到相关员工");
                return resDto;
            }
            //已经离职
            if (employeeInfo.getStatus() == Common.EMPLOYEE_STATUS_DIMISSION || employeeInfo.getStatus() == Common.EMPLOYEE_STATUS_WORKING) {
                continue;
            }
            if (employeeInfo.getStatus() == Common.EMPLOYEE_STATUS_VOCATION) {
                employeeInfo.setStatus(Common.EMPLOYEE_STATUS_WORKING);
                employeeInfo.setModifiedTime(new Date());
                employeeInfos.add(employeeInfo);
            }
        }
        if (!employeeInfos.isEmpty()) {
            boolean updateInfo = employeeInfoService.updateBatchById(employeeInfos);
            if (!updateInfo) {
                ResDto resDto = new ResDto(ConstEum.PARAM_ERROR);
                resDto.setMsg("修改失败");
                return resDto;
            }
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @PostMapping(value = "/edit")
    @ResponseBody
    public ResDto editEmployee(AddEmployeeInfoDTO infoDTO) {
        if (null == infoDTO) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 根据员工号获取员工信息
        AfEmployeeInfo employeeInfo = employeeInfoService.getEmployeeInfoByEmpNo(infoDTO.getEmpNo());
        if (null == employeeInfo) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }

        employeeInfo.setPostId(infoDTO.getPostId());
        employeeInfo.setPostName(infoDTO.getPostName());
        employeeInfo.setDeptId(infoDTO.getDeptId());
        employeeInfo.setDeptName(infoDTO.getDeptName());
        employeeInfo.setJobId(infoDTO.getJobId());
        employeeInfo.setJobName(infoDTO.getJobName());
        employeeInfo.setModifiedTime(new Date());
        boolean update = employeeInfoService.updateById(employeeInfo);
        if (!update) {
            ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("修改错误");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @PostMapping(value = "/info/state")
    @ResponseBody
    public ResDto updateEmployeeState(String empId, Integer state) {
        ResDto resDto;
        if (StringUtils.isBlank(empId) || state == null || (state != Common.DATA_STATE_NORMAL && state != Common.DATA_STATE_DELETE)) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            return resDto;
        }
        //获取访客状态
        AfEmployeeInfo afEmployeeInfo = employeeInfoService.selectById(empId);
        if (null == afEmployeeInfo) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("未获取到相关员工");
            return resDto;
        }
        if (state == Common.DATA_STATE_NORMAL) {
            afEmployeeInfo.setState(Common.DATA_STATE_DELETE);
        } else {
            afEmployeeInfo.setState(Common.DATA_STATE_NORMAL);
        }
        afEmployeeInfo.setModifiedTime(new Date());

        boolean update = employeeInfoService.updateById(afEmployeeInfo);
        if (!update) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("更新员工状态失败");
            return resDto;
        }
        resDto = new ResDto(ConstEum.SUCCESS);
        resDto.setDatas(afEmployeeInfo.getState()+"");
        return resDto;
    }

    @PostMapping(value = "/schedul/create")
    @ResponseBody
    public ResDto createSchedulCreate(MultipartFile file, String name, Integer type) {
        ResDto resDto;
        if (file == null || StringUtils.isBlank(name) || type == null || (type != Common.ROSTER_CROSS_TYPE_OVERDAY &&
        type != Common.ROSTER_CROSS_TYPE_ONEDAY)) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 根据名称和类型
        AfRosterInfo rosterInfo = rosterInfoService.getRosterInfo(name, type);
        if (null == rosterInfo) {
            rosterInfo = new AfRosterInfo();
            rosterInfo.setName(name);
            rosterInfo.setCross(type);
            String rosterId = rosterInfoService.addRosterInfo(rosterInfo);
            if (StringUtils.isBlank(rosterId)) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("新增班次失败");
                return resDto;
            }
            rosterInfo.setId(rosterId);
        }
        //读取信息
        try {
            Map<String, Object> readExcelEmployeeInfo = POIUtil.readExcelSchedule(file.getBytes(), file.getOriginalFilename());
            if (null == readExcelEmployeeInfo || readExcelEmployeeInfo.isEmpty()) {
                return new ResDto(ConstEum.PARAM_ERROR);
            }
            List<AfRosterDetail> rosterInfos = (List<AfRosterDetail>) readExcelEmployeeInfo.get("rosterDetails");
            if (null == rosterInfo || rosterInfos.isEmpty()) {
                return new ResDto(ConstEum.PARAM_ERROR);
            }
            List<AfRosterDetail> insertDetails = new ArrayList<>();
            for (AfRosterDetail detail : rosterInfos) {
                AfEmployeeInfo afEmployeeInfo = employeeInfoService.getEmployeeInfoByEmpNo(detail.getEmpNo());
                if (null == afEmployeeInfo) {
                    log.error("未查询到相关员工信息 {}", JsonMapper.defaultMapper().toJson(detail));
                    continue;
                }
                detail.setId(IdGeneratorUtil.uuid());
                detail.setState(Common.DATA_STATE_NORMAL);
                detail.setRosterId(rosterInfo.getId());
                detail.setRosterName(rosterInfo.getName());
                //TODO
                //detail.setBeforeRosterId();
                detail.setDeptId(afEmployeeInfo.getDeptId());
                detail.setEmpId(afEmployeeInfo.getId());
                detail.setJobId(afEmployeeInfo.getJobId());
                Date currentDate = new Date();
                detail.setCreateTime(currentDate);
                detail.setModifiedTime(currentDate);
                insertDetails.add(detail);
            }

            boolean batch = rosterDetailService.insertBatch(insertDetails);
            if (!batch) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("导入失败");
                return resDto;
            }
        } catch (Exception e) {
            e.printStackTrace();
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("导入失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @GetMapping(value = "/schedul/download/template")
    @ResponseBody
    public void downLoadScheduleTemplete(HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        excelSupport.downLoadTemplete(httpServletRequest, httpServletResponse, "schedul.xls");
    }

    @GetMapping(value = "/schedule/export")
    public void exportSchedulDetails(@RequestParam("id")String rosterId, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        List<AfRosterDetail> details = rosterDetailService.getRosterInfoDetails(rosterId);
        List<ExportRosterDetailExcel> infoDTOS = new ArrayList<>();
        if (null != details && !details.isEmpty()) {
            infoDTOS = details.stream().map(guestInfo -> {
                ExportRosterDetailExcel dto = new ExportRosterDetailExcel();
                BeanUtils.copyProperties(guestInfo, dto);
                return dto;
            }).collect(Collectors.toList());
        }
        ExcelSupport.Content<ExportRosterDetailExcel> content = new ExcelSupport.Content<>("班次人员名单", infoDTOS, ExportRosterDetailExcel.class);
        excelSupport.export(httpServletRequest, httpServletResponse, "班次人员信息.xls", content);
    }

    @PostMapping(value = "/schedul/import")
    @ResponseBody
    public ResDto createSchedulCreate(MultipartFile file) {
        ResDto resDto;
        if (file == null) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        //读取信息
        try {
            Map<String, Object> readExcelSchClass = POIUtil.readExcelSchClass(file.getBytes(), file.getOriginalFilename());
            if (null == readExcelSchClass || readExcelSchClass.isEmpty()) {
                return new ResDto(ConstEum.PARAM_ERROR);
            }
            List<AfRosterInfo> rosters = (List<AfRosterInfo>) readExcelSchClass.get("rosters");
            if (null == rosters || rosters.isEmpty()) {
                return new ResDto(ConstEum.PARAM_ERROR);
            }
            List<AfRosterInfo> insertInfo = new ArrayList<>();
            for (AfRosterInfo info : rosters) {
                AfRosterInfo rosterInfo = rosterInfoService.getRosterInfo(info.getName(), info.getCross());
                if (null != rosterInfo) {
                    log.info("已存在相关班次信息 {}", JsonMapper.defaultMapper().toJson(rosterInfo));
                    continue;
                }
                rosterInfo = new AfRosterInfo();
                rosterInfo.setId(IdGeneratorUtil.uuid());
                rosterInfo.setState(Common.DATA_STATE_NORMAL);
                rosterInfo.setName(info.getName());
                rosterInfo.setCross(info.getCross());
                Date currentDate = new Date();
                rosterInfo.setCreateTime(currentDate);
                rosterInfo.setModifiedTime(currentDate);
                insertInfo.add(rosterInfo);
            }
            boolean batch = rosterInfoService.insertBatch(insertInfo);
            if (!batch) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("导入失败");
                return resDto;
            }
        } catch (Exception e) {
            e.printStackTrace();
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("导入失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @PostMapping(value = "/schedul/edit")
    @ResponseBody
    public ResDto editSchedule(String rosterId, String name, Integer cross, String addEmpNos, String removeEmpNos, String otherRosterId) {
        if (StringUtils.isBlank(rosterId) || StringUtils.isBlank(name) || cross == null || (cross != Common.ROSTER_CROSS_TYPE_OVERDAY &&
        cross != Common.ROSTER_CROSS_TYPE_ONEDAY)) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 获取排班信息
        AfRosterInfo rosterInfo = rosterInfoService.selectById(rosterId);
        if (null == rosterInfo) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        AfRosterInfo dbRosterInfo = rosterInfoService.getRosterInfo(name, cross);
        if (null != dbRosterInfo) {
            if (!rosterInfo.getId().equals(dbRosterInfo.getId())) {
                ResDto resDto = new ResDto(ConstEum.PARAM_ERROR);
                resDto.setMsg("排班信息已存在无法修改");
                return resDto;
            }
        } else {
            rosterInfo.setCross(cross);
            rosterInfo.setName(name);
            rosterInfo.setModifiedTime(new Date());
            boolean update = rosterInfoService.updateById(rosterInfo);
            if (!update) {
                log.error("修改班次信息失败 {}", JsonMapper.defaultMapper().toJson(rosterInfo));
                ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("修改班次信息失败");
                return resDto;
            }
            // 更新所有排班详情中的排班名称
           int result = rosterDetailService.updateRosterInfo(rosterId, name);
            if (result == Common.RETURN_FAILED) {
                return new ResDto(ConstEum.SERVER_ERROR);
            }
        }
        //判断调整班次是否存在
        if (StringUtils.isBlank(otherRosterId)) {
            return new ResDto(ConstEum.SUCCESS);
        }
        // 获取另外的排班
        AfRosterInfo otherRosterInfo = rosterInfoService.selectById(otherRosterId);
        if (otherRosterInfo == null) {
            ResDto resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("调整班次参数有误");
            return resDto;
        }
        List<String> addEmpNoList = new ArrayList<>();
        List<String> removeEmpNoList = new ArrayList<>();
        // A 部门新增的即为B 部门移除的
        if (StringUtils.isNotBlank(addEmpNos)) {
            String[] addEmps = addEmpNos.split(",");
            addEmpNoList.addAll(Arrays.asList(addEmps));
        }
        if (StringUtils.isNotBlank(removeEmpNos)) {
            String[] removeEmps = removeEmpNos.split(",");
            removeEmpNoList.addAll(Arrays.asList(removeEmps));
        }
        List<AfRosterDetail> updateDetais = new ArrayList<>();
        for (String empNo : addEmpNoList) {
            //获取人员信息
            AfRosterDetail detail = rosterDetailService.getRosterInfoDetailByEmpNoAndRosterId(empNo, otherRosterId);
            if (detail != null) {
                detail.setBeforeRosterId(otherRosterId);
                detail.setRosterId(rosterId);
                detail.setRosterName(rosterInfo.getName());
                detail.setModifiedTime(new Date());
                updateDetais.add(detail);
            } else {
                log.error("调班是添加员工未在另一个班次中查询到 {}", empNo);
                continue;
            }
        }

        for (String empNo : removeEmpNoList) {
            //获取人员信息
            AfRosterDetail detail = rosterDetailService.getRosterInfoDetailByEmpNoAndRosterId(empNo, rosterId);
            if (detail != null) {
                detail.setBeforeRosterId(rosterId);
                detail.setRosterId(otherRosterId);
                detail.setRosterName(otherRosterInfo.getName());
                detail.setModifiedTime(new Date());
                updateDetais.add(detail);
            } else {
                log.error("调班时删除员工未在另一个班次中查询到 {}", empNo);
                continue;
            }
        }

        boolean updateBatch = rosterDetailService.updateBatchById(updateDetais);
        if (!updateBatch) {
            log.error("更新排班人员信息失败 {}", JsonMapper.defaultMapper().toJson(updateDetais));
            ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("更新人员排班信息失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    /**
     * 根据id获取部门名称
     * @param deptId 部门id
     * @return 部门名称
     */
    public String getDeptName(String deptId) {
        if(StringUtils.isNotBlank(deptId)) {
            AfDepartment departmentInfo = departmentService.getDepartmentInfo(deptId);
            if (null != departmentInfo) {
                return departmentInfo.getName();
            }
        }
        return null;
    }

    /**
     * 根据岗位id 获取岗位名称
     * @param postId 岗位id
     * @return 岗位名称
     */
    public String getPostName(String postId) {
        if(StringUtils.isNotBlank(postId)) {
            AfPost post = postService.getPostById(postId);
            if (null != post) {
                return post.getName();
            }
        }
        return null;
    }

    /**
     * 根据工种id 获取工种名称
     * @param jobId 工种id
     * @return 工种名称
     */
    public String getJobName(String jobId) {
        if(StringUtils.isNotBlank(jobId)) {
            AfJob job = jobService.getJobById(jobId);
            if (null != job) {
                return job.getName();
            }
        }
        return null;
    }

}
